﻿using MCPlatform.Communicate.SerialPorts;
using MCPlatform.MotionLib.Base;
using MCPlatform.MotionLib.Base.AssitantClass;
using Newtonsoft.Json;
using Panuon.WPF;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;

namespace MCPlatform.UI.Controls.Models
{
    public class SerialPortModel : NotifyPropertyChangedBase, INameProvider
    {
        #region Properties
        [Newtonsoft.Json.JsonIgnore]
        public SerialPort SerialPort { get => _SerialPort; set => Set(ref _SerialPort, value); }

        [Newtonsoft.Json.JsonIgnore]
        private SerialPort _SerialPort = new SerialPort();


        [Newtonsoft.Json.JsonIgnore]
        public ISerialPort? ISerialPort { get => _iSerialPort; set => Set(ref _iSerialPort, value); }

        [Newtonsoft.Json.JsonIgnore]
        private ISerialPort? _iSerialPort;

     
        public string ControlName { get => _ControlName; set => Set(ref _ControlName, value); }
        private string _ControlName = string.Empty;

        public string PortName { get => _PortName; set => Set(ref _PortName, value); }
        private string _PortName = string.Empty;

        public int BaudRate { get => _BaudRate; set => Set(ref _BaudRate, value); }
        private int _BaudRate = 115200;


        public int DataBits { get => _DataBits; set => Set(ref _DataBits, value); }
        private int _DataBits = 8;

        public string Parity { get => _Parity; set => Set(ref _Parity, value); }
        private string _Parity = "None";

        public int StopBits { get => _StopBits; set => Set(ref _StopBits, value); }
        private int _StopBits = 1;

        public bool IsOpen 
        { 
            get
            {
                if (SerialPort is null)
                {
                    return false;
                }
                _IsOpen = SerialPort.IsOpen;
                return _IsOpen;
            } 

            set => Set(ref _IsOpen, value); }
        private bool _IsOpen = true;


        #endregion

        public SerialPortModel()
        {
          
          
        }

        public void MappingComInfoToSerialPort()
        {

            _SerialPort.PortName = this.PortName;
            _SerialPort.BaudRate = this.BaudRate;
            _SerialPort.DataBits = this.DataBits;
            _SerialPort.Parity = (Parity)Enum.Parse(typeof(Parity), this.Parity);
            _SerialPort.StopBits = (StopBits)Enum.Parse(typeof(StopBits), this.StopBits.ToString());

            _iSerialPort = new SerialPortComm(_SerialPort);

        }

    }
}
